<template>
  <div>
    <vxe-form size="small" :data="formData" v-show="queryFromShow">
      <vxe-form-item  v-if="queryFromShow" v-for="(item,index) in queryFields" :title="item.title" :field="item.field" :key="index"
                     :item-render="{}">
        <template #default="{ data }">
          <div v-if="item.query==='between'">
              <Between :type="item.types===4?'date':'text'" v-model="data[item.field]"></Between>
          </div>
          <div v-else>
            <vxe-input   v-model="data[item.field]" placeholder="请输入条件值"  @keyup="parseCode({event:$event,field:item,data:data})"></vxe-input>
          </div>

        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <vxe-button size="small" v-if="queryFromShow" @click="getList(1)" status="primary">查询</vxe-button>
          <vxe-button size="small" v-if="queryFromShow" type="reset">重置</vxe-button>
          <vxe-button size="small" @click="exportSelectEvent">导出</vxe-button>
        </template>
      </vxe-form-item>
    </vxe-form>

    <vxe-table border  size="mini" height="800" show-overflow :data="list"  ref="Table"  :sync-resize="resize"
               :exportConfig="{ type: 'xlsx',modes: ['current', 'all']}"
               :column-config="{resizable: true}"
               :row-config="{isCurrent: true, isHover: true}"  :loading="loading"
               :show-footer="ShowFooter"
               :footer-method="footerMethod">
      <vxe-column type="seq"  width="60"></vxe-column>
      <vxe-column :width="item.allowFixedWidth>0?item.allowFixedWidth:150" sortable type="html" min-width="80"  v-for="item in Fields" :field="item.fieldName"  :visible="item.hidden===0"  :key="item.fieldID" :title="item.fieldDispName" >   </vxe-column>
    </vxe-table>
    <vxe-pager size="mini" perfect :loading="loading" v-model:current-page="MainPage.pageNum"  v-model:page-size="MainPage.pageSize"
               :page-sizes="[10, 20, 50,100,500, 1000, {label: '全量数据', value: -1}]" :total="MainPage.totalResult"
               :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
               @page-change="MainPageChange">
    </vxe-pager>
  </div>
</template>

<script>
import {onBeforeMount, reactive, ref, toRefs} from "vue";
import {useRoute, useRouter} from 'vue-router'
import XEUtils from "xe-utils";
import {getTemplate,getSelectRule,} from "/@/api/linkoo/form"
import {ElMessage} from "element-plus";

import Between from '/@/views/views/components/between.vue';

export default {
  name: "views",
  components:{Between},
  setup(){
    const route = useRoute()
    const Table = ref(null)
    let state = reactive({
      MainPage: {pageNum: 1, pageSize: 200, totalResult: 0},
      filterName:'',
      TableData:[],
      Fields:[],
      list:[],
      queryFields:[],
      queryFieldsType:{},
      SelectRules:[],
      loading:false,
      queryFromShow:false,
      formData:{},
      rulesNum:0,
      query:0,
      resize: '0',
      template:{},
      ShowFooter: false,
      FooterFields: [],
      load:false,
    })
    onBeforeMount(()=>{
      getInfo()
    })
    const searchEvent1=()=>{
      const filterName = XEUtils.toValueString(state.filterName).trim().toLowerCase()
      if (filterName) {
        const filterRE = new RegExp(filterName, 'gi')
        const searchProps =  XEUtils.pluck(state.Fields, 'fieldName')
        const rest = state.TableData.filter(item => searchProps.some(key => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1))
        state.list = rest.map(row => {
          const item = Object.assign({}, row)
          searchProps.forEach(key => {
            item[key] = XEUtils.toValueString(item[key]).replace(filterRE, match => `<span class="keyword-lighten">${match}</span>`)
          })
          return item
        })
      } else {
        state.list = state.TableData
      }
    }
    const exportSelectEvent = () => {
      const $table = Table.value
      // $table.openExport()
      $table.exportData({
        filename:XEUtils.toDateString(new Date(), 'yyyyMMddHHmmssSSS'),
        sheetName: 'Sheet1',
        type:'xlsx',
        data: $table.getTableData().fullData
      })
    }
    const getInfo = ()=>{
      state.loading=true
      getTemplate(route.path.replace('/form/','')).then(response => {
        if(response['code']===undefined){
          setTimeout(()=>{getInfo()},1000)
        }
        state.MainTable = response.data.tables.filter(item => item.tableType === 0)[0]
        if(state.MainTable['onSheet']!==''){
          state.FooterFields=state.MainTable['onSheet'].split(',')

         state.ShowFooter=true
        }

        state.template = response.data.template
        state.ActRules = XEUtils.orderBy(response.data.actRules?response.data.actRules.filter(item=>item.ruleType===1):[], 'runSeq')
        const rule= XEUtils.find(state.ActRules,item=>item.runSeq===0)
        const sf= XEUtils.toStringJSON(rule.targetField)
        state.MainTable.Fields.forEach(field => {
            state.Fields.push(field)
              if (field.fieldAreaName!==''){
                let sff=XEUtils.find(sf,item=>item.tofield===field.fieldName||item.tofield===state.MainTable.tableName+'.'+field.fieldName)
                state.queryFields.push({title:field.fieldDispName,field:sff.field,query:field.fieldAreaName,types:field.dataTypeID,fields:field})
                state.queryFromShow=true
              }

        })
        getList(0)
      })
    }
    const getList= async (q)=>{
      state.query=q
        let selectrules = XEUtils.filter(state.ActRules, item => item.runTime.split(',').includes('108') || item.runTime.split(',').includes('102')|| item.runTime.split(',').includes('999'))
        for (let i = 0; i < selectrules.length; i++) {
          await GetSelectRules(selectrules[i], '')
      }
      state.loading=false
    }
    const MainPageChange = ({currentPage, pageSize}) => {
      state.MainPage.pageNum = currentPage
      state.MainPage.pageSize = pageSize
      // store.state.themeConfig.themeConfig.page[]=pageSize
      state.selectMainData = null
      getList(1)
    }
    const GetSelectRules = async (rule, filterExpr) => {
      if(filterExpr===''){
         filterExpr = rule.filterExpr
        const regex = /({(\S+)[.](\S+)})/gis
        let m
        let keys = [], table = [], vals = []
        while ((m = regex.exec(filterExpr)) !== null) {
          // 这对于避免零宽度匹配的无限循环是必要的
          if (m.index === regex.lastIndex) {
            regex.lastIndex++
          }
          m.forEach((match, groupIndex) => {
            if (groupIndex === 1) {
              keys.push(match)
            }
            if (groupIndex === 2) {
              table.push(match)
            }
            if (groupIndex === 3) {
              vals.push(match)
            }
          })
        }
        const $tb=Table.value
        XEUtils.arrayEach(keys, (it, key) => {
          if (filterExpr.indexOf(' in ') > 1) {
            const data = XEUtils.pluck(XEUtils.clone($tb.getTableData().fullData, true), vals[key])
            filterExpr = filterExpr.replace(it, `'${data.join("','")}'`)
          } else {
            let val = XEUtils.get(state.formData, vals[key], '')
            if (val.length === 0) {
              const data = $tb.getCurrentRecord()
              val = XEUtils.get(data, vals[key], "")
            }

            filterExpr = filterExpr.replace(it, val)
          }
        })
      }
      if(state.query===1){
        const FF=[]
        XEUtils.arrayEach(state.queryFields,f=>{
          if (XEUtils.toValueString(state.formData[f.field])!==''){
            if(f.query==='like'){
              FF.push(XEUtils.template(" {{field}} like '%{{name}}%' ", {name: XEUtils.toValueString(state.formData[f.field]),field:f.field}))
            }else if(f.query==='between'){
              FF.push(XEUtils.template(" {{field}} between '{{name[0]}}' and '{{name[1]}}' ", {name: XEUtils.toValueString(state.formData[f.field]).split(","),field:f.field}))
            }else{
              FF.push(XEUtils.template(" {{field}} {{query}} '{{name}}' ", {query:f.query,name: XEUtils.toValueString(state.formData[f.field]),field:f.field}))
            }
          }
        })
        filterExpr=filterExpr===''?FF.join('and'):filterExpr+' and '+FF.join('and')
      }
      await getSelectRule(rule.ruleID, filterExpr,state.MainPage.pageNum,state.MainPage.pageSize).then(res => {
        if (res.data.list) {
          state.MainPage.totalResult=res.data.total
          fromSelectRule(rule, res.data.list)
          ElMessage.success('成功执行[' + rule.ruleName + '],数据已添加')
        } else {
          ElMessage({type: 'info', message: '成功执行[' + rule.ruleName + '],但未到取到数据',})
        }
      })
    }
    const fromSelectRule = (rule, data) => {
      if (data === null) return
      const topull = JSON.parse(rule['targetField'])
      let TB = {},link=false,linkstr=''
      topull.forEach(row => {
        const tf = row['tofield'].split('.')
        if (TB[tf[0]] === undefined) TB[tf[0]] = {}
        TB[tf[0]][tf[1]] =row['field'].indexOf('.')>-1? row['field'].split('.')[1]:row['field']
        if(row.type==='keys'){
          link=true
          linkstr=tf[1]
        }
      })

      XEUtils.objectEach(TB, (fields, key) => {
            const $tb = Table.value
            let records = []
            data.forEach(row => {
              let record = {}
              XEUtils.objectEach(fields, (f, t) => {
                record[t] = row[f]
              })

              records.push(record)
            })
            if (rule.clearAllRow === 1) {
              $tb.remove()
            }
            if(link){
              const dd=XEUtils.clone($tb.getTableData().fullData,true)
              dd.map(row=>{
                const record=XEUtils.find(records,r=>r[linkstr]===row[linkstr])
                if(record){
                  XEUtils.objectEach(record,(item,key)=>{
                    row[key]=item
                  })
                }
                return row
              })
              $tb.reloadData(dd)
            }else {
              $tb.insertAt(records, -1)
            }
            state.resize = key
        state.TableData=$tb.getTableData().fullData

      })
    }
    const footerMethod = ({ columns, data }) => {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }

          if (state.FooterFields.includes(column.field)) {
            return sumNum(data, column.field)
          }
          return null
        })
      ]
    }
    const sumNum = (list, field) => {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count
    }
    const parseCode=({event,field,data})=>{
      if(event.$event.keyCode===13){
        if (field.fields.componentType===8&& field.fields.componentFieldName !== ''){
          const  codes=XEUtils.toStringJSON(field.fields.componentFieldName)
          if(data[field.field]&&data[field.field].split(codes['separator']).length===codes['count']){
            data[field.field]=data[field.field].split(codes['separator'])[codes['size']]
          }
        }
          setTimeout(()=>{
            getList(1)
          },50)
        }
    }
    return {
      getList,
      Table,
      ...toRefs(state),
      MainPageChange,
      footerMethod,
      searchEvent1,parseCode,
      exportSelectEvent,
    }
  }
}
</script>

<style >
.keyword-lighten {
  color: #000;
  background-color: #FFFF00;
}

</style>